package socket_test;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/*
tcp协议的连接 要三次"挥手"   关闭连接要4次"挥手"
 */
public class Client {
    private Socket socket;
    public Client(){
        try {
            System.out.println("正在连接服务器");
            socket = new Socket("localhost",8090);
            System.out.println("连接成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start(){
        Scanner sc = new Scanner(System.in);
        try {
            OutputStream os = socket.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(os, StandardCharsets.UTF_8);
            BufferedWriter bw = new BufferedWriter(osw);
            PrintWriter pw = new PrintWriter(bw,true);
            while (true) {
                System.out.println("请输入");
                String data = sc.nextLine();
                if ("exit".equals(data)){
                    System.out.println("关闭");
                    break;
                }
                pw.println(data);
            }
            pw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        Client client = new Client();
        client.start();
    }
}
